import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter/widgets.dart';
import '../../common/index.dart';
import 'package:image_picker/image_picker.dart';
import '../myPlant/controller.dart';

class PlantDetailController extends GetxController {
  PlantDetailController({Plant? plant}) {
    if (plant != null) {
      this.plant = plant;
      debugPrint("从构造函数接收到植物数据: ${plant.name}, ID: ${plant.id}");
      // 如果有图片，立即初始化排序后的日期键列表
      if (plant.image_list.isNotEmpty) {
        sorted_date_keys = plant.image_list.keys.toList()
          ..sort((a, b) => b.compareTo(a));
        debugPrint("从构造函数加载植物历史图片: ${sorted_date_keys.length}张");
      } else {
        sorted_date_keys = [];
        debugPrint("植物没有历史图片");
      }
    }
  }

  // 当前展示的植物
  late Plant plant;

  // 排序后的图片时间列表
  List<String> sorted_date_keys = [];

  // 加载状态
  RxBool is_loading = false.obs;

  // 图片选择器
  final ImagePicker _imagePicker = ImagePicker();

  // 将日期转换为显示格式
  String formatDate(String dateKey) {
    try {
      final parts = dateKey.split('-');
      if (parts.length != 3) return dateKey;

      final year = parts[0];
      final month = int.parse(parts[1]);
      final day = int.parse(parts[2]);

      final months = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December',
      ];

      String suffix = 'th';
      if (day % 10 == 1 && day != 11) {
        suffix = 'st';
      } else if (day % 10 == 2 && day != 12) {
        suffix = 'nd';
      } else if (day % 10 == 3 && day != 13) {
        suffix = 'rd';
      }

      return '$year\n${months[month - 1]} $day$suffix';
    } catch (e) {
      debugPrint("日期格式转换错误: $e");
      return dateKey;
    }
  }

  // 判断日期是否为今天
  bool is_today(String dateKey) {
    final today = DateTime.now();
    final formattedToday =
        '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';
    return dateKey == formattedToday;
  }

  // 判断日期是否为昨天
  bool is_yesterday(String dateKey) {
    final yesterday = DateTime.now().subtract(Duration(days: 1));
    final formattedYesterday =
        '${yesterday.year}-${yesterday.month.toString().padLeft(2, '0')}-${yesterday.day.toString().padLeft(2, '0')}';
    return dateKey == formattedYesterday;
  }

  // 获取今天的日期键
  String _get_today_date_key() {
    final today = DateTime.now();
    return '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';
  }

  // 选择图片
  Future<void> pick_and_upload_image() async {
    try {
      is_loading.value = true;
      update(["plant_detail"]);

      final XFile? picked_image = await _imagePicker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 85,
      );

      if (picked_image == null) {
        debugPrint("未选择图片");
        return;
      }

      await _save_image_to_plant(picked_image);
    } catch (e) {
      debugPrint("选择图片失败: $e");
    } finally {
      is_loading.value = false;
      update(["plant_detail"]);
    }
  }

  // 拍摄照片
  Future<void> take_and_upload_photo() async {
    try {
      final XFile? taken_photo = await _imagePicker.pickImage(
        source: ImageSource.camera,
        imageQuality: 85,
      );

      if (taken_photo == null) {
        debugPrint("未拍摄照片");
        return;
      }

      await _save_image_to_plant(taken_photo);
    } catch (e) {
      debugPrint("拍摄照片失败: $e");
    }
  }

  // 保存图片到植物历史记录
  Future<void> _save_image_to_plant(XFile imageFile) async {
    try {
      // 保存图片到本地存储
      final String savedPath = await ImageStorageService().save_image(
        imageFile,
      );
      if (savedPath.isEmpty) {
        debugPrint("保存图片失败");
        return;
      }

      // 获取今天的日期键
      final String today_key = _get_today_date_key();

      // 检查是否已经有今天的图片
      if (plant.image_list.containsKey(today_key)) {
        // 如果存在今天的图片，删除旧图片
        final String oldImagePath = plant.image_list[today_key]!;
        await ImageStorageService().delete_image(oldImagePath);
        debugPrint("已删除今天的旧图片: $oldImagePath");
      }

      // 更新植物的image_list
      final Map<String, String> updated_image_list = Map.from(plant.image_list);
      updated_image_list[today_key] = savedPath;

      // 创建更新后的植物对象
      final updated_plant = plant.copyWith(image_list: updated_image_list);

      // 保存更新后的植物数据
      await Storage().set_json("plant_${plant.id}", updated_plant.toJson());

      // 更新当前植物对象
      plant = updated_plant;

      // 确保在PlantService中也更新植物数据，这样应用的其他部分也能访问到最新数据
      await PlantService().get_plant_by_id(plant.id).then((cachedPlant) {
        if (cachedPlant != null) {
          // 如果MyPlant页面的控制器存在，通知它更新植物数据
          if (Get.isRegistered<MyPlantController>()) {
            final myPlantController = Get.find<MyPlantController>();
            final index = myPlantController.plants.indexWhere(
              (p) => p.id == plant.id,
            );
            if (index >= 0) {
              myPlantController.plants[index] = updated_plant;
              myPlantController.update(["my_plant"]);
            }
          }
        }
      });

      // 更新排序后的日期键列表
      _update_sorted_date_keys();

      update(["plant_detail"]);

      debugPrint("已成功添加今天的植物历史图片");
    } catch (e) {
      debugPrint("保存植物历史图片失败: $e");
    }
  }

  // 更新排序后的日期键列表
  void _update_sorted_date_keys() {
    sorted_date_keys = plant.image_list.keys.toList()
      ..sort((a, b) => b.compareTo(a));
  }

  _initData() {
    try {
      // 如果在构造函数中已经收到植物数据，则无需再从路由获取
      if (plant != null) {
        debugPrint("已通过构造函数接收植物数据，跳过路由数据获取");
        update(["plant_detail"]);
        return;
      }

      debugPrint("开始从路由参数获取植物详情数据...");

      try {
        if (Get.context != null) {
          final extra = GoRouterState.of(Get.context!).extra;
          debugPrint("GoRouter extra的数据类型: ${extra?.runtimeType}");

          if (extra is Plant) {
            plant = extra;
            debugPrint("成功从GoRouter获取植物数据: ${plant.name}, ID: ${plant.id}");

            // 按时间倒序排列图片键值
            if (plant.image_list.isNotEmpty) {
              sorted_date_keys = plant.image_list.keys.toList()
                ..sort((a, b) => b.compareTo(a));
              debugPrint("加载植物历史图片: ${sorted_date_keys.length}张");
            } else {
              debugPrint("植物没有历史图片");
              sorted_date_keys = [];
            }

            update(["plant_detail"]);
            return;
          }
        }
      } catch (e) {
        debugPrint("获取GoRouter extra时出错: $e");
      }

      // 如果无法获取植物数据，返回上一页
      debugPrint("错误: 无法获取植物数据");
      WidgetsBinding.instance.addPostFrameCallback((_) {
        RouteUtil.pop();
      });
    } catch (e, stack_trace) {
      debugPrint("初始化植物详情数据错误: $e");
      debugPrint("错误堆栈: $stack_trace");

      // 延迟返回上一页，避免在构建过程中导航
      WidgetsBinding.instance.addPostFrameCallback((_) {
        RouteUtil.pop();
      });
    }
  }

  void onTap() {}

  @override
  void onInit() {
    super.onInit();
    _initData();
  }

  @override
  void onReady() {
    super.onReady();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
